# -*- coding: utf-8 -*-
# @Author : want_login
# @Time : 2019/11/20 上午9:31

from qiniu import Auth,put_file,etag,put_data
QINIU_ACCESS_KEY = 'ee7DUIjFVPssTMSPkXDkL7I14ZPkzQ9vUix5LV2j'
QINIU_SECRET_KEY = 'aCpM-Kei5CMhtSnc0KmHMeA72nj06TL5mBzk8O0a'
QINIU_BUCKET_NAME = 'zhanghaha-house-img'

def storage(file_data):
    """
    上传文件
    :param file_data:  要上传的文件
    :return:    返回URL
    """
    # 创建授权对象
    q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)

    # 生成一个上传的token
    token = q.upload_token(QINIU_BUCKET_NAME,None,7200)

    ret,info = put_data(token,None,file_data)

    if info.status_code == 200:
        #success
        return ret.get('key')
    else:
        #fault
        raise Exception("上传失败")
    # print(info)
    # print("*"*10)
    # print(ret)
    # assert ret['key']== key
    # assert ret['hash'] == etag(localfile)

# if __name__ == '__main__':
#     with open("./IMG_0380.jpg",'rb')as f:
#         file_data = f.read()
#         storage(file_data)


from django.contrib.auth.mixins import LoginRequiredMixin
from django import http
class LoginRequiredJSONMixin(LoginRequiredMixin):
    """自定义判断用户是否登陆的拓展类：返回json"""

    def handle_no_permission(self):
        # 为什么只需要重写handle_no_permission，因为判断用户是否登陆的操作父类已经完成
        return http.JsonResponse({'code': "用户未登录", 'errmsg': '用户未登录'})